/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Dao.AlunoDao;
import Dao.AlunoDaoImplJPA;
import Dao.AtividadeDao;
import Dao.AtividadeDaoImplJPA;
import Dao.DisciplinaDao;
import Dao.DisciplinaDaoImplJPA;
import Dao.HistoricoTurmaDao;
import Dao.HistoricoTurmaDaoImplJPA;
import Dao.ProfessorDao;
import Dao.ProfessorDaoImplJPA;
import Dao.TurmaDao;
import Dao.TurmaDaoImplJPA;
import Pojo.Aluno;
import Pojo.Atividade;
import Pojo.Disciplina;
import Pojo.Professor;
import Pojo.Turma;
import java.awt.Color;
import java.util.List;
import javax.swing.ComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author thiago
 */
public class FormCadastroTurmas extends javax.swing.JInternalFrame {

    String modificacao;
    private Professor professor;

    /**
     * Setter de modificação
     * @param modificacao 
     */
    public void setModificacao(String modificacao) {
        this.modificacao = modificacao;
    }

    /**
     * Getter de modificação
     * @return 
     */
    public String getModificacao() {
        return modificacao;
    }
    
    /**
     * Creates new form FormCadastroTurmas
     */
    public FormCadastroTurmas() {
        initComponents();
        this.buscarProfessores();
        this.buscarDisciplinas();
        cbbProfessor.setSelectedItem("");
        cbbDisciplina.setSelectedItem("");
    }
    
    /**
     * @param codigo
     * Constutor FormCadastroTurmas carregando pelo código
     */
    public FormCadastroTurmas(int codigo) {
        initComponents();
        this.buscarProfessores();
        this.buscarDisciplinas();
        cbbProfessor.setSelectedItem("");
        cbbDisciplina.setSelectedItem("");
        this.carregarDadosCampos(codigo);
    }
    
    /**
     * Cria a lista de alunos no comboBox
     */
    private void buscarDisciplinas(){
        DisciplinaDao alunoDao = new DisciplinaDaoImplJPA();
        List<Disciplina> listaDisciplinas = alunoDao.pesquisarTodos();
        for(Disciplina disciplina : listaDisciplinas){
            cbbDisciplina.addItem(disciplina.getId()+" - "+disciplina.getNome());
        }
    }
    
    /**
     * Cria a lusta de professores no comboBox
     */
    private void buscarProfessores(){
        ProfessorDao professorDao = new ProfessorDaoImplJPA();
        List<Professor> listaProfessores = professorDao.pesquisarTodos();
        for(Professor professor : listaProfessores){
            cbbProfessor.addItem(professor.getId()+" - "+professor.getNome());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblCodigo = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        lblAno = new javax.swing.JLabel();
        txtAno = new javax.swing.JTextField();
        lblPeriodo = new javax.swing.JLabel();
        txtPeriodo = new javax.swing.JTextField();
        lblLocalizacao = new javax.swing.JLabel();
        txtLocalizacao = new javax.swing.JTextField();
        txtHorario = new javax.swing.JTextField();
        lblHorario = new javax.swing.JLabel();
        txtNumeroVagas = new javax.swing.JTextField();
        lblNumeroVagas = new javax.swing.JLabel();
        lblNumeroVagas1 = new javax.swing.JLabel();
        cbbProfessor = new javax.swing.JComboBox();
        cbbDisciplina = new javax.swing.JComboBox();
        lblNumeroVagas2 = new javax.swing.JLabel();
        lblSituacao = new javax.swing.JLabel();
        lblSituacao1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        btnNovo = new javax.swing.JButton();
        btnAlterar = new javax.swing.JButton();
        btnRemover = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setClosable(true);
        setTitle("Cadastro de Turmas");
        setPreferredSize(new java.awt.Dimension(600, 338));

        lblCodigo.setText("Código");

        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
        });

        lblAno.setText("Ano");

        txtAno.setEnabled(false);

        lblPeriodo.setText("Período");

        txtPeriodo.setEnabled(false);

        lblLocalizacao.setText("Localização");

        txtLocalizacao.setEnabled(false);

        txtHorario.setEnabled(false);

        lblHorario.setText("Horário");

        txtNumeroVagas.setEnabled(false);

        lblNumeroVagas.setText("Número de Vagas");

        lblNumeroVagas1.setText("Professor");

        cbbProfessor.setEnabled(false);

        cbbDisciplina.setEnabled(false);

        lblNumeroVagas2.setText("Disciplina");

        lblSituacao.setText("Situação");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(txtPeriodo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
                                .addComponent(lblCodigo, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtCodigo, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lblAno, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(txtAno, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(lblPeriodo, javax.swing.GroupLayout.Alignment.LEADING))
                            .addComponent(lblLocalizacao)
                            .addComponent(lblHorario)
                            .addComponent(txtHorario, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 117, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(lblNumeroVagas)
                                .addComponent(txtNumeroVagas, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(lblNumeroVagas1)
                                .addComponent(cbbProfessor, 0, 174, Short.MAX_VALUE)
                                .addComponent(lblNumeroVagas2)
                                .addComponent(cbbDisciplina, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(lblSituacao))
                            .addComponent(lblSituacao1)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtLocalizacao, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblCodigo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblAno)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblPeriodo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPeriodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblNumeroVagas)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNumeroVagas, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblNumeroVagas1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbbProfessor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblNumeroVagas2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbbDisciplina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblLocalizacao)
                    .addComponent(lblSituacao))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtLocalizacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblSituacao1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(lblHorario)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtHorario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
        );

        btnNovo.setText("Novo");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });

        btnAlterar.setText("Alterar");
        btnAlterar.setEnabled(false);
        btnAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarActionPerformed(evt);
            }
        });

        btnRemover.setText("Remover");
        btnRemover.setEnabled(false);
        btnRemover.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoverActionPerformed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.setEnabled(false);
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.setEnabled(false);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnNovo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnAlterar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnRemover, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnSalvar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnNovo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnAlterar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnRemover)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnSalvar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnCancelar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void carregarDadosCampos(int codigo){
        TurmaDao turmaDao = new TurmaDaoImplJPA();
        Turma turma = turmaDao.pesquisarPorId(codigo);

        if (turma != null){
            txtCodigo.setText(String.valueOf(codigo));
            txtAno.setText(String.valueOf(turma.getAno()));
            txtPeriodo.setText(String.valueOf(turma.getPeriodo()));
            txtLocalizacao.setText(turma.getLocalizacao());
            txtHorario.setText(turma.getHorario());
            txtNumeroVagas.setText(String.valueOf(turma.getNumeroDeVagas()));  
            cbbProfessor.setSelectedItem(turma.getProfessor().getId()+" - "+turma.getProfessor().getNome());
            cbbDisciplina.setSelectedItem(turma.getDisciplina().getId()+" - "+turma.getDisciplina().getNome());
            if (turma.getFinalizada()==true){
                lblSituacao1.setText("Finalizada");
                lblSituacao1.setForeground(Color.red);
            }else{
                lblSituacao1.setText("Aberta");
                lblSituacao1.setForeground(Color.blue);
            }

            btnNovo.setEnabled(true);
            btnAlterar.setEnabled(true);
            btnRemover.setEnabled(true);
            btnSalvar.setEnabled(false);
            btnCancelar.setEnabled(false);
        } else {
            JOptionPane.showMessageDialog(null, "Não existe uma turma com esse código.");
            txtAno.setText("");
            txtPeriodo.setText("");
            txtLocalizacao.setText("");
            txtHorario.setText("");
            txtNumeroVagas.setText("");

            btnNovo.setEnabled(true);
            btnAlterar.setEnabled(false);
            btnRemover.setEnabled(false);
            btnSalvar.setEnabled(false);
            btnCancelar.setEnabled(false);

        }
    }
    
    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed

        txtCodigo.setEnabled(false);
        txtAno.setEnabled(true);
        txtPeriodo.setEnabled(true);
        txtLocalizacao.setEnabled(true);
        txtHorario.setEnabled(true);
        txtNumeroVagas.setEnabled(true);
        cbbDisciplina.setEnabled(true);
        cbbProfessor.setEnabled(true);

        txtAno.setText("");
        txtPeriodo.setText("");
        txtLocalizacao.setText("");
        txtHorario.setText("");
        txtNumeroVagas.setText("");
        
        btnNovo.setEnabled(false);
        btnAlterar.setEnabled(false);
        btnRemover.setEnabled(false);
        btnSalvar.setEnabled(true);
        btnCancelar.setEnabled(true);

        txtAno.grabFocus();
        this.setModificacao("N");
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarActionPerformed
        if (txtCodigo.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe uma turma para ser alterado.");
        }else if (lblSituacao1.getText()=="Finalizada"){
            JOptionPane.showMessageDialog(null, "Não é possível alterar a turma que já foi finalizada.");
        }else{
            txtCodigo.setEnabled(false);
            txtAno.setEnabled(true);
            txtPeriodo.setEnabled(true);
            txtLocalizacao.setEnabled(true);
            txtHorario.setEnabled(true);
            txtNumeroVagas.setEnabled(true);
            cbbDisciplina.setEnabled(true);
            cbbProfessor.setEnabled(true);

            btnNovo.setEnabled(false);
            btnAlterar.setEnabled(false);
            btnRemover.setEnabled(false);
            btnSalvar.setEnabled(true);
            btnCancelar.setEnabled(true);

            txtAno.grabFocus();
            this.setModificacao("A");
        }
    }//GEN-LAST:event_btnAlterarActionPerformed

    private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
        if (txtCodigo.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe uma turma para ser removido.");
        }else{
            if (JOptionPane.showConfirmDialog(null, "Deseja remover a turma?")==0){
                
                //buscando a turma
                boolean finalizada = false;
                if (lblSituacao1.getText().equals("Finalizada")){
                    finalizada = true;
                }
                Turma turma = new Turma(Integer.parseInt(txtCodigo.getText()),Integer.parseInt(txtAno.getText()),Integer.parseInt(txtPeriodo.getText()),txtLocalizacao.getText(),txtHorario.getText(),Integer.parseInt(txtNumeroVagas.getText()),finalizada);
                TurmaDao turmaDao = new TurmaDaoImplJPA();
                
                //Verificando se esta já foi finalizada
                if (turma.getFinalizada()==true){
                    JOptionPane.showMessageDialog(null, "Impossível remover uma turma que já está finalizada.");
                    return;
                }
                
                //verificando se existe algum aluno matriculado na turma.
                HistoricoTurmaDao historicoTurmaDao = new HistoricoTurmaDaoImplJPA();
                List<Aluno> listaAlunos = historicoTurmaDao.pesquisarAlunosTurma(turma);
                if (listaAlunos.size()>0){
                    JOptionPane.showMessageDialog(null, "Impossível remover uma turma na qual já foram matriculados alunos.");
                    return;
                }
                
                //verificando se alguma atividade já foi inserida.
                AtividadeDao atividadeDao = new AtividadeDaoImplJPA();
                List<Atividade> listaAtividade = atividadeDao.pesquisarPorTurma(turma);
                if (listaAlunos.size()>0){
                    JOptionPane.showMessageDialog(null, "Impossível remover uma turma na qual já foram lançadas atividades.");
                    return;
                }
                
                if (turmaDao.remover(turma)==true){

                    txtCodigo.setEnabled(true);
                    txtAno.setEnabled(false);
                    txtPeriodo.setEnabled(false);
                    txtLocalizacao.setEnabled(false);
                    txtHorario.setEnabled(false);
                    txtNumeroVagas.setEnabled(false);
                    cbbDisciplina.setEnabled(false);
                    cbbProfessor.setEnabled(false);

                    txtCodigo.setText("");
                    txtAno.setText("");
                    txtPeriodo.setText("");
                    txtLocalizacao.setText("");
                    txtHorario.setText("");
                    txtNumeroVagas.setText("");
                    lblSituacao1.setText("");
                    cbbDisciplina.setSelectedItem("");
                    cbbProfessor.setSelectedItem("");

                    btnNovo.setEnabled(true);
                    btnAlterar.setEnabled(false);
                    btnRemover.setEnabled(false);
                    btnSalvar.setEnabled(false);
                    btnCancelar.setEnabled(false);

                    JOptionPane.showMessageDialog(null, "Turma removido com sucesso.");
                }else{
                    JOptionPane.showMessageDialog(null, "Erro ao remover o turma.");
                }
            }
        }
    }//GEN-LAST:event_btnRemoverActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed

        TurmaDao turmaDao = new TurmaDaoImplJPA();
        Turma turma;
        String[] dados;
        Professor professor;
        Disciplina disciplina;
        ProfessorDao professorDao = new ProfessorDaoImplJPA();
        DisciplinaDao disciplinaDao = new DisciplinaDaoImplJPA();
        boolean salvo = false;

        if (txtAno.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe o ano da turma.");
            return;
        }

        if (txtPeriodo.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe o periodo da turma.");
            return;
        }

        if (txtLocalizacao.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe a localização da turma.");
            return;
        }
        
        if (txtHorario.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe o horário da turma.");
            return;
        }
        
       if (txtNumeroVagas.getText().length()==0){
            JOptionPane.showMessageDialog(null, "Informe o número de vagas na turma.");
            return;
        }
       
        String professorString = (String) cbbProfessor.getSelectedItem();
        if (professorString.length()==0){
            JOptionPane.showMessageDialog(null, "Informe o professor que lecionará essa turma.");
            return;
        }else{
            dados = professorString.split(" - ");
            professor = professorDao.pesquisarPorId(Integer.parseInt(dados[0]));
        }
        
        String disciplinaString = (String) cbbDisciplina.getSelectedItem();
        if (disciplinaString.length()==0){
            JOptionPane.showMessageDialog(null, "Informe a disciplina dessa turma.");
            return;
        }else{
            dados = disciplinaString.split(" - ");
            disciplina = disciplinaDao.pesquisarPorId(Integer.parseInt(dados[0])); 
        }

        if (this.getModificacao().equals("A")){
            turma = turmaDao.pesquisarPorId(Integer.parseInt(txtCodigo.getText()));
            if (turma.getFinalizada()==true){
                 JOptionPane.showMessageDialog(null, "Impossível alterar essa turma. Ela já foi finalizada.");
                 return;
            }            
            turma = new Turma(Integer.parseInt(txtCodigo.getText()),Integer.parseInt(txtAno.getText()),Integer.parseInt(txtPeriodo.getText()),txtLocalizacao.getText(),txtHorario.getText(),Integer.parseInt(txtNumeroVagas.getText()),false,professor,disciplina);
            if (turmaDao.alterar(turma)==true){
                JOptionPane.showMessageDialog(null, "Turma alterada com sucesso.");
                salvo = true;
            }else{
                JOptionPane.showMessageDialog(null, "Erro ao alterar o turma.");
                salvo = false;
            }
        }else if (this.getModificacao().equals("N")){
            turma = new Turma(Integer.parseInt(txtAno.getText()),Integer.parseInt(txtPeriodo.getText()),txtLocalizacao.getText(),txtHorario.getText(),Integer.parseInt(txtNumeroVagas.getText()),false,professor,disciplina);

            if (turmaDao.inserir(turma)==true){
                JOptionPane.showMessageDialog(null, "Turma inserida com sucesso.");
                salvo = true;
            }else{
                JOptionPane.showMessageDialog(null, "Erro ao inserir o turma.");
                salvo = false;
            }
        }

        if (salvo == true){
            txtCodigo.setEnabled(true);
            txtAno.setEnabled(false);
            txtPeriodo.setEnabled(false);
            txtLocalizacao.setEnabled(false);
            txtHorario.setEnabled(false);
            txtNumeroVagas.setEnabled(false);
            cbbDisciplina.setEnabled(false);
            cbbProfessor.setEnabled(false);

            txtCodigo.setText("");
            txtAno.setText("");
            txtPeriodo.setText("");
            txtLocalizacao.setText("");
            txtHorario.setText("");
            txtNumeroVagas.setText("");
            lblSituacao1.setText("");
            cbbDisciplina.setSelectedItem("");
            cbbProfessor.setSelectedItem("");

            btnNovo.setEnabled(true);
            btnAlterar.setEnabled(false);
            btnRemover.setEnabled(false);
            btnSalvar.setEnabled(false);
            btnCancelar.setEnabled(false);

            this.setModificacao("");

            txtCodigo.grabFocus();
        }
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        txtCodigo.setEnabled(true);
        txtAno.setEnabled(false);
        txtPeriodo.setEnabled(false);
        txtLocalizacao.setEnabled(false);
        txtHorario.setEnabled(false);
        txtNumeroVagas.setEnabled(false);
        cbbDisciplina.setEnabled(false);
        cbbProfessor.setEnabled(false);

        txtCodigo.setText("");
        txtAno.setText("");
        txtPeriodo.setText("");
        txtLocalizacao.setText("");
        txtHorario.setText("");
        txtNumeroVagas.setText("");
        lblSituacao1.setText("");
        cbbDisciplina.setSelectedItem("");
        cbbProfessor.setSelectedItem("");

        btnNovo.setEnabled(true);
        btnAlterar.setEnabled(false);
        btnRemover.setEnabled(false);
        btnSalvar.setEnabled(false);
        btnCancelar.setEnabled(false);
        
        txtCodigo.grabFocus();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        if (evt.getKeyCode() == 10){
            int codigo;
            try{
                codigo = Integer.parseInt(txtCodigo.getText());
            }catch(Exception e){
                return;
            }
            this.carregarDadosCampos(codigo);
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnRemover;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JComboBox cbbDisciplina;
    private javax.swing.JComboBox cbbProfessor;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel lblAno;
    private javax.swing.JLabel lblCodigo;
    private javax.swing.JLabel lblHorario;
    private javax.swing.JLabel lblLocalizacao;
    private javax.swing.JLabel lblNumeroVagas;
    private javax.swing.JLabel lblNumeroVagas1;
    private javax.swing.JLabel lblNumeroVagas2;
    private javax.swing.JLabel lblPeriodo;
    private javax.swing.JLabel lblSituacao;
    private javax.swing.JLabel lblSituacao1;
    private javax.swing.JTextField txtAno;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtHorario;
    private javax.swing.JTextField txtLocalizacao;
    private javax.swing.JTextField txtNumeroVagas;
    private javax.swing.JTextField txtPeriodo;
    // End of variables declaration//GEN-END:variables
}
